package com.rzico.quartz.job;

import com.rzico.account.entity.Foundation;
import com.rzico.account.service.FoundationService;
import com.rzico.basics.entity.Vip;
import com.rzico.basics.service.VipService;
import com.rzico.core.entity.SysJob;
import com.rzico.core.service.SysJobService;
import com.rzico.order.entity.Shipping;
import com.rzico.order.enumx.ShippingStatusEnum;
import com.rzico.order.service.ShippingService;
import org.apache.commons.lang3.time.DateUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by zhongzm on 2020/2/2.
 * 计划任务执行demo
 */
public class FoundationQuartz implements Job {

    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    protected SysJobService sysJobService;

    @Autowired
    protected FoundationService foundationService;

    @Autowired
    protected VipService vipService;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String jobId = jobExecutionContext.getTrigger().getKey().getName();
        SysJob sysJob = sysJobService.selectByPrimaryKey(jobId);
        try {
            if (sysJob.getExecStatus().equals(1)) {
                //不能重复执行
                return;
            }
            sysJob.setExecStatus(1);
            sysJob.setJobDesc("开始执行:"+sdf.format(new Date()));
            sysJobService.updateByPrimaryKeySelective(sysJob);

            Map<String,Object> param = new HashMap<>();

            List<Vip> vipList = vipService.selectList(param);
            for (Vip vip:vipList) {
                foundationService.jobTask(vip);
            }

            sysJob.setExecStatus(0);
            sysJob.setJobDesc("执行成功:"+sdf.format(new Date())+",下次执行:"+sdf.format(jobExecutionContext.getNextFireTime()));
            sysJobService.updateByPrimaryKeySelective(sysJob);
        }
        catch (Exception e) {
            sysJob.setExecStatus(0);
            sysJob.setJobDesc("执行错误:"+sdf.format(new Date()));
            sysJobService.updateByPrimaryKeySelective(sysJob);
        }

    }
}
